package kk.yiyi.safedesign.warming;

import android.app.Activity;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import kk.yiyi.safedesign.base.Constants;
import kk.yiyi.safedesign.base.MessageEvent;
import kk.yiyi.safedesign.base.SharePresenterUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WarmingService {
    public void warmSelect(final Activity activity)
    {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder().add("uphone", SharePresenterUtils.getData(activity,Constants.TABLE,"user"))
                .build();
        final Request request = new Request.Builder()
                .url(Constants.WARM_SELECT)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("demo","warming失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //解析php返回的json数据
                parseAllShopping(response,activity);
            }
        });

    }

    private void parseAllShopping(Response response, final Activity activity) throws IOException {
        //获取json数据
        String responseData=response.body().string();
        Log.d("mgl:登录信息",responseData);
        try{
            JSONArray jsonArray=new JSONArray(responseData);
            for(int i=0;i<jsonArray.length();i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String result = jsonObject.getString("check");
                if (result.equals("1")) {
                    EventBus.getDefault().post(new MessageEvent("warming","暂无记录"));
                }else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                WarmingService warmingService=new WarmingService();
                                warmingService.warmSelect(activity);
                                Thread.sleep(2000);
                                return;
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
